package com.zyg.cod.util;


import com.csii.credit.annotation.CommenElement;
import com.csii.credit.annotation.FieldXmlAnnotation;
import com.csii.credit.annotation.SubNodeAnnotation;
import com.csii.credit.annotation.TableXmlAnnotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/***
 * 报文生成和解析工具类
 * @author allen-zyg
 * 2017年11月27日
 *
 */
@SuppressWarnings("all")
public class Bean2XmlUtils {

	/**
	 * 反馈报文内容读取方法：特定格式的
	 * xml2bean
	 */
	public List<Object> xml2bean(String fullName) {


		return null;
	}


	/***
	 * 将bean转换成XML报文  线程阻塞
	 * 这个方法只针对二代征信报文生成
	 * @des
	 * @param map
	 * @param class1
	 * @return
	 */
	public synchronized static String bean2Xml(Object obj) {
		StringBuffer xmlbuffer = null;
		//如果是大类节点，则获取属性名称，作为下一级的标签名字
		List nodeList = null;
		Object type = null;
		String commentField = null;
		Object comFieldValue = null;
		String subNode = null;
		CommenElement commentannotation = null;
		SubNodeAnnotation subNodeAnnotation = null;
		FieldXmlAnnotation fieldXmlAnnotation = null;
		TableXmlAnnotation twoXmlAnnotation = null;
		TableXmlAnnotation threeAnnotation = null;
		try {
			xmlbuffer = new StringBuffer();
			//获得Obj所有的属性:这是每个类的列表
			Field[] fields = obj.getClass().getDeclaredFields();
			if (fields == null) {
				throw new RuntimeException("实体对象属性为空");
			}
			//获得Obj对象注解，并获得注解值
			twoXmlAnnotation = obj.getClass().getAnnotation(TableXmlAnnotation.class);
			String twoNodeName = twoXmlAnnotation.ElementFromName().toString();
			//打印大类节点：<!--StudentVO-->
			if (twoNodeName != null && !twoNodeName.equals("")) {
				xmlbuffer.append("<Document><" + twoNodeName + ">");
			}
			//遍历ObjVO所有的属性列表
			for (Field field : fields) {
				//获取列表的值(list)
				nodeList = (List) getFieldValueByName(field.getName(), obj);
				//如果list不为null,直接采用第一个元素的来生成，否则采用
				int size = 0;
				if (nodeList == null || nodeList.isEmpty()) {
					//就不打印了：空值校验
					continue;
				} else {
					size = nodeList.size();
					type = nodeList.get(0);
				}
				threeAnnotation = type.getClass().getAnnotation(TableXmlAnnotation.class);  //nodeList.get(0)空指针异常
				String threeNodeName = threeAnnotation.ElementFromName();
				if (threeNodeName != null && !threeNodeName.equals("")) {
					xmlbuffer.append("<" + threeNodeName + ">");
				}
				Field[] fields3 = type.getClass().getDeclaredFields();
				//判断当前节点是否是一对多的关系: 标识为 2
				int relationType = threeAnnotation.RelationType();
				if (relationType == 2) {
					//先取一对多实体的，公共字段，
					for (Field f3 : fields3) {
						//获取公共字段：
						commentannotation = f3.getAnnotation(CommenElement.class);
						if (commentannotation != null) {
							commentField = commentannotation.ElementName();
							//公共字段的值
							comFieldValue = getFieldValueByName(f3.getName(), nodeList.get(0)); //公共字段是每项一样的
							if (comFieldValue instanceof Date) {
								String dateString = com.csii.credit.util.DateUtil.getDateStr((Date) comFieldValue);
								xmlbuffer.append("<" + commentField + ">" + dateString + "</" + commentField + ">");
							} else {
								xmlbuffer.append("<" + commentField + ">" + comFieldValue + "</" + commentField + ">");
							}
						}
						//获取子节点的外层标签
						subNodeAnnotation = f3.getAnnotation(SubNodeAnnotation.class);
						if (subNodeAnnotation != null) {
							subNode = subNodeAnnotation.ElementName();
						}
					}
					for (int i = 0; i < size; i++) {
						xmlbuffer.append("<" + subNode + ">");
						//获得当前的列表对象的属性的注解
						for (Field f3 : fields3) {
							//排除公共字段和和外层
							commentannotation = f3.getAnnotation(CommenElement.class);
							subNodeAnnotation = f3.getAnnotation(SubNodeAnnotation.class);
							if (commentannotation == null & subNodeAnnotation == null) {
								fieldXmlAnnotation = f3.getAnnotation(FieldXmlAnnotation.class);
								String FieldName = f3.getName();
								String ElementName = fieldXmlAnnotation.ElementName().toString();
								//判断是否为不必要打印字段
								boolean need = fieldXmlAnnotation.isNeed();
								if (!need) {
									continue;
								}
								//判断属性上xml标示注解名是否为空
								if (ElementName != null && !ElementName.equals("")) {
									//得到属性的get方法
									String getFieldName = "get" + FieldName.substring(0, 1).toUpperCase() + "" + FieldName.substring(1, FieldName.length());
									Method method = nodeList.get(i).getClass().getDeclaredMethod(getFieldName);
									if (method != null) {
										//得到属性的值:注意其类型
										Object value = method.invoke(nodeList.get(i));
										xmlbuffer.append("<" + ElementName + ">");
										if (value instanceof Date) {
											xmlbuffer.append(com.csii.credit.util.DateUtil.getDateStr((Date) value));
										} else if (value == null) {
											xmlbuffer.append("");
										} else {
											xmlbuffer.append(value);
										}
										xmlbuffer.append("</" + ElementName + ">"); //xmlbuffer.append("</"+ElementName+">");
									}
								}
							}
							//
						}
						xmlbuffer.append("</" + subNode + ">");
					}

				} else {
					//获得当前的列表对象的属性的注解
					for (Field f3 : fields3) {
						fieldXmlAnnotation = f3.getAnnotation(FieldXmlAnnotation.class);
						String FieldName = f3.getName();
						String ElementName = fieldXmlAnnotation.ElementName().toString();
						//判断是否为不必要打印字段
						boolean need = fieldXmlAnnotation.isNeed();
						if (!need) {
							continue;
						}
						//判断属性上xml标示注解名是否为空
						if (ElementName != null && !ElementName.equals("")) {
							//得到属性的get方法
							String getFieldName = "get" + FieldName.substring(0, 1).toUpperCase() + "" + FieldName.substring(1, FieldName.length());
							Method method = type.getClass().getDeclaredMethod(getFieldName);
							if (method != null) {
								//得到属性的值:注意其类型
								Object value = method.invoke(type);
								//拼装XML
								xmlbuffer.append("<" + ElementName + ">");
								if (value instanceof Date) {
									xmlbuffer.append(com.csii.credit.util.DateUtil.getDateStr((Date) value));
								} else if (value == null) {
									xmlbuffer.append("");
								} else {
									xmlbuffer.append(value);
								}
								xmlbuffer.append("</" + ElementName + ">"); //xmlbuffer.append("</"+ElementName+">");
							}
						}

					}
				}
				if (threeNodeName != null && !threeNodeName.equals("")) {
					xmlbuffer.append("</" + threeNodeName + ">");
				}

			}
			if (twoNodeName != null && !twoNodeName.equals("")) {
				xmlbuffer.append("</" + twoNodeName + "></Document>\n");
			}
		} catch (Exception e) {
			//异常处理
			e.printStackTrace();
		}
		return xmlbuffer.toString();
	}

	/**
	 * 获取属性类型(type)，属性名(name)，属性值(value)的map组成的list
	 */
	private static List getFiledsInfo(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		List list = new ArrayList();
		Map infoMap = null;
		for (int i = 0; i < fields.length; i++) {
			infoMap = new HashMap();
			infoMap.put("type", fields[i].getType().toString());
			infoMap.put("name", fields[i].getName());
			infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
			list.add(infoMap);
		}
		return list;
	}

	/**
	 * 根据对象属性名称获取属性值
	 *
	 * @param fieldName
	 * @param o
	 * @return
	 */
	private static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[]{});
			Object value = method.invoke(o, new Object[]{});
			return value;
		} catch (Exception e) {
			return null;
		}
	}
}
